/* Copyright (C) 2011 clueless <clueless.mmopeon@gmail.com>
 *
 * This file is part of MMO Peon.
 *
 * MMO Peon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MMO Peon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MMO Peon.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cstdint>
#include <windows.h>
#include <sstream>
#include <cmath>
#include <cstddef>
#include "commontypes.h"
#include "classes/objectmap.h"
#include "logic.h"
#include "log.h"
#include "packets.h"
#include "classes/waypoints.h"
#include "classes/movement.h"
#include "states/movement.h"
#include "states/harvest.h"

HANDLE logicThread;
DWORD __stdcall LogicMain(void *dummy);

void LogicInit()
{
    logicThread = CreateThread(0, 0, &LogicMain, 0, 0, 0);
}

void LogicFree()
{
    TerminateThread(logicThread, 0);
}

DWORD __stdcall LogicMain(void *dummy)
{
    std::ostringstream wpFile;
    wpFile << getenv("APPDATA") << "\\howlingmountains.xml";
    Waypoints   wps(wpFile.str());
    PlayerMovement movement(memBase);
    HarvestState harvestState(&movement);
    MovementState moveState(&movement, &wps);
    StateMachine fsm;
    fsm.AddState(&moveState);
    fsm.AddState(&harvestState);

    while (true)
    {
        Sleep(50);
        fsm.Pulse();
    }

    return 0;
}

HWND GetRomWindowHandle()
{
    HWND romWindow = GetTopWindow(0);
    while (romWindow)
    {
        DWORD pid;
        GetWindowThreadProcessId(romWindow ,&pid);
        if (pid == GetCurrentProcessId())
            return romWindow;

        romWindow = GetNextWindow(romWindow, GW_HWNDNEXT);
    }

    return 0;
}

void SendKey(int key)
{
    HWND romWindow = NULL;
    DWORD pid;
    while ((romWindow = FindWindowEx(NULL, romWindow, "Radiant Arcana", "Runes of Magic")) != NULL)
    {
        GetWindowThreadProcessId(romWindow, &pid);
        if (pid == GetCurrentProcessId())
        {
            PostMessage(romWindow, WM_KEYDOWN, key, 0);
            PostMessage(romWindow, WM_KEYUP, key, 0);
        }
    }
}
